package com.unity.bh3.controller;

import com.unity.bh3.common.Result;
import com.unity.bh3.dto.BatchRemoveCharacterRequest;
import com.unity.bh3.dto.BatchRemoveItemRequest;
import com.unity.bh3.dto.InventoryItemDTO;
import com.unity.bh3.dto.PurchaseRequest;
import com.unity.bh3.dto.UserCharacterDTO;
import com.unity.bh3.service.InventoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.util.List;

/**
 * 背包控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/inventory")
@Tag(name = "背包管理", description = "背包相关接口")
@Validated
public class InventoryController {
    
    @Autowired
    private InventoryService inventoryService;
    

    
    /**
     * 获取用户拥有的角色列表
     */
    @GetMapping("/characters/{userId}")
    @Operation(summary = "获取用户角色列表", description = "获取指定用户拥有的角色列表")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<List<UserCharacterDTO>> getUserCharacters(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId) {
        
        log.info("获取用户角色列表，用户ID: {}", userId);
        
        try {
            List<UserCharacterDTO> characters = inventoryService.getUserCharacters(userId);
            return Result.success("获取用户角色列表成功", characters);
        } catch (Exception e) {
            log.error("获取用户角色列表失败，用户ID: {}", userId, e);
            return Result.failed("获取用户角色列表失败");
        }
    }
    
    /**
     * 获取用户拥有的角色ID列表
     */
    @GetMapping("/character-ids/{userId}")
    @Operation(summary = "获取用户角色ID列表", description = "获取指定用户拥有的角色ID列表")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<List<Long>> getUserCharacterIds(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId) {
        
        log.info("获取用户角色ID列表，用户ID: {}", userId);
        
        try {
            List<Long> characterIds = inventoryService.getUserCharacterIds(userId);
            return Result.success("获取用户角色ID列表成功", characterIds);
        } catch (Exception e) {
            log.error("获取用户角色ID列表失败，用户ID: {}", userId, e);
            return Result.failed("获取用户角色ID列表失败");
        }
    }
    

    

    
    /**
     * 添加物品到背包（带类型）
     */
    @PostMapping("/add-item-with-type/{userId}")
    @Operation(summary = "添加物品到背包（带类型）", description = "添加物品到用户背包，并指定物品类型")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<String> addItemToInventoryWithType(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "物品ID", required = true)
            @RequestParam @NotNull @Positive Long itemId,
            @Parameter(description = "数量", required = true)
            @RequestParam @NotNull @Positive Integer quantity,
            @Parameter(description = "物品类型 (1:武器, 2:圣痕, 3:材料, 4:碎片)", required = true)
            @RequestParam @NotNull @Positive Integer itemType) {
        
        log.info("添加物品到背包（带类型），用户ID: {}, 物品ID: {}, 数量: {}, 类型: {}", userId, itemId, quantity, itemType);
        
        // 验证物品类型
        if (itemType < 1 || itemType > 4) {
            return Result.failed("物品类型无效，必须为1-4之间的数字");
        }
        
        try {
            boolean success = inventoryService.addItemToInventory(userId, itemId, quantity, itemType);
            if (success) {
                return Result.success("添加物品成功");
            } else {
                return Result.failed("添加物品失败");
            }
        } catch (Exception e) {
            log.error("添加物品到背包失败，用户ID: {}, 物品ID: {}, 数量: {}, 类型: {}", userId, itemId, quantity, itemType, e);
            return Result.failed("添加物品失败");
        }
    }
    
    /**
     * 根据类型获取背包物品ID列表
     */
    @GetMapping("/items-by-type/{userId}")
    @Operation(summary = "根据类型获取背包物品ID列表", description = "根据物品类型获取用户背包中的物品ID列表")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<List<Long>> getInventoryItemIdsByType(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "物品类型 (1:武器, 2:圣痕, 3:材料, 4:碎片)", required = true)
            @RequestParam @NotNull @Positive Integer itemType) {
        
        log.info("根据类型获取背包物品ID列表，用户ID: {}, 物品类型: {}", userId, itemType);
        
        // 验证物品类型
        if (itemType < 1 || itemType > 4) {
            return Result.failed("物品类型无效，必须为1-4之间的数字");
        }
        
        try {
            List<Long> itemIds = inventoryService.getInventoryItemIdsByType(userId, itemType);
            return Result.success("获取物品ID列表成功", itemIds);
        } catch (Exception e) {
            log.error("根据类型获取背包物品ID列表失败，用户ID: {}, 物品类型: {}", userId, itemType, e);
            return Result.failed("获取物品ID列表失败");
        }
    }
    
    /**
     * 添加角色到用户
     */
    @PostMapping("/add-character/{userId}")
    @Operation(summary = "添加角色到用户", description = "直接添加角色到用户")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<String> addCharacterToUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "角色ID", required = true)
            @RequestParam @NotNull @Positive Long characterId) {
        
        log.info("添加角色到用户，用户ID: {}, 角色ID: {}", userId, characterId);
        
        try {
            boolean success = inventoryService.addCharacterToUser(userId, characterId);
            if (success) {
                return Result.success("添加角色成功");
            } else {
                return Result.failed("添加角色失败，可能已拥有该角色");
            }
        } catch (Exception e) {
            log.error("添加角色到用户失败，用户ID: {}, 角色ID: {}", userId, characterId, e);
            return Result.failed("添加角色失败");
        }
    }
    
    /**
     * 删除背包物品
     */
    @DeleteMapping("/remove-item/{userId}")
    @Operation(summary = "删除背包物品", description = "从用户背包中删除指定数量的物品")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<String> removeItemFromInventory(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "物品ID", required = true)
            @RequestParam @NotNull @Positive Long itemId,
            @Parameter(description = "删除数量", required = true)
            @RequestParam @NotNull @Positive Integer quantity) {
        
        log.info("删除背包物品，用户ID: {}, 物品ID: {}, 数量: {}", userId, itemId, quantity);
        
        try {
            boolean success = inventoryService.removeItemFromInventory(userId, itemId, quantity);
            if (success) {
                return Result.success("删除物品成功");
            } else {
                return Result.failed("删除物品失败，物品不存在或数量不足");
            }
        } catch (Exception e) {
            log.error("删除背包物品失败，用户ID: {}, 物品ID: {}, 数量: {}", userId, itemId, quantity, e);
            return Result.failed("删除物品失败");
        }
    }
    
    /**
     * 删除用户角色
     */
    @DeleteMapping("/remove-character/{userId}")
    @Operation(summary = "删除用户角色", description = "从用户中删除指定角色")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<String> removeCharacterFromUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "角色ID", required = true)
            @RequestParam @NotNull @Positive Long characterId) {
        
        log.info("删除用户角色，用户ID: {}, 角色ID: {}", userId, characterId);
        
        try {
            boolean success = inventoryService.removeCharacterFromUser(userId, characterId);
            if (success) {
                return Result.success("删除角色成功");
            } else {
                return Result.failed("删除角色失败，角色不存在");
            }
        } catch (Exception e) {
            log.error("删除用户角色失败，用户ID: {}, 角色ID: {}", userId, characterId, e);
            return Result.failed("删除角色失败");
        }
    }
    
    /**
     * 批量删除背包物品（同一类型）
     */
    @DeleteMapping("/remove-items/{userId}")
    @Operation(summary = "批量删除背包物品（同一类型）", description = "从用户背包中批量删除同一类型的多个物品")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<String> removeMultipleItemsFromInventory(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "批量删除物品请求", required = true)
            @RequestBody @Valid BatchRemoveItemRequest request) {
        
        log.info("批量删除背包物品（同一类型），用户ID: {}, 请求: {}", userId, request);
        
        try {
            boolean success = inventoryService.removeMultipleItemsFromInventory(
                userId, request.getItemIds(), request.getQuantities(), request.getItemType());
            if (success) {
                return Result.success("批量删除物品成功");
            } else {
                return Result.failed("批量删除物品失败，请检查物品是否存在、数量是否足够或类型是否匹配");
            }
        } catch (Exception e) {
            log.error("批量删除背包物品失败，用户ID: {}, 请求: {}", userId, request, e);
            return Result.failed("批量删除物品失败");
        }
    }
    
    /**
     * 批量删除用户角色
     */
    @DeleteMapping("/remove-characters/{userId}")
    @Operation(summary = "批量删除用户角色", description = "从用户中批量删除多个角色")
    @Parameters({
            @Parameter(name = "User-Id", ref = "User-Id")
    })
    public Result<String> removeMultipleCharactersFromUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Positive Long userId,
            @Parameter(description = "批量删除角色请求", required = true)
            @RequestBody @Valid BatchRemoveCharacterRequest request) {
        
        log.info("批量删除用户角色，用户ID: {}, 请求: {}", userId, request);
        
        try {
            boolean success = inventoryService.removeMultipleCharactersFromUser(
                userId, request.getCharacterIds());
            if (success) {
                return Result.success("批量删除角色成功");
            } else {
                return Result.failed("批量删除角色失败，请检查角色是否存在");
            }
        } catch (Exception e) {
            log.error("批量删除用户角色失败，用户ID: {}, 请求: {}", userId, request, e);
            return Result.failed("批量删除角色失败");
        }
    }
}